import jsPDF from "jspdf";
import html2canvas from "html2canvas";

/**
 * 将 HTMLCanvasElement 插入到 jsPDF 实例中，自动分页。
 * @param {jsPDF} pdf jsPDF 实例
 * @param {HTMLCanvasElement} canvas 要插入的画布
 */
export function insertCanvasToPdf(pdf, canvas, options = {}) {
  if (!canvas || !pdf) return;
  const { imageType = "JPEG", quality = 0.7 } = options; // 默认使用 JPEG 并压缩
  const pdfWidth = pdf.internal.pageSize.getWidth();
  const pageHeight = pdf.internal.pageSize.getHeight();
  const imgData = canvas.toDataURL(`image/${imageType.toLowerCase()}`, quality);
  const imgHeight = (canvas.height * pdfWidth) / canvas.width;
  let position = 0;
  let heightLeft = imgHeight;
  pdf.addImage(
    imgData,
    imageType,
    0,
    position,
    pdfWidth,
    imgHeight,
    undefined,
    "FAST"
  );
  heightLeft -= pageHeight;
  while (heightLeft > 0) {
    position -= pageHeight;
    pdf.addPage();
    pdf.addImage(
      imgData,
      imageType,
      0,
      position,
      pdfWidth,
      imgHeight,
      undefined,
      "FAST"
    );
    heightLeft -= pageHeight;
  }
}

/**
 * 创建新的 jsPDF 并插入一个 canvas，返回生成的 pdf 对象（未保存）。
 * @param {HTMLCanvasElement} canvas 画布
 * @param {Object} options jsPDF 选项
 */
export function createPdfFromCanvas(canvas, options = {}) {
  const pdf = new jsPDF("p", "mm", "a4", options);
  insertCanvasToPdf(pdf, canvas);
  return pdf;
}

/**
 * 导出包含多个 section 的元素为 PDF。
 * @param {HTMLElement} rootEl 根容器元素（包含标题、统计卡片和若干 section）
 * @param {string} sectionSelector section 元素选择器，默认 '.analysis-section'
 * @param {string} filename 输出文件名
 */
export async function exportElementWithSections(
  rootEl,
  sectionSelector = ".analysis-section",
  filename = "report.pdf",
  options = { scale: 1, quality: 0.7, includeFirstSectionInFirstPage: false }
) {
  if (!rootEl) return;
  const pdf = new jsPDF("p", "mm", "a4");

  // helper
  const addCanvas = (canvas) => insertCanvasToPdf(pdf, canvas, options);

  // 所有 section 节点
  const sections = Array.from(rootEl.querySelectorAll(sectionSelector));

  // ------------- 首页：标题 + 统计卡片 + 第一张表 -------------
  if (sections.length > 0) {
    const firstPageClone = rootEl.cloneNode(true);
    firstPageClone.style.width = rootEl.clientWidth + "px";
    const nodes = firstPageClone.querySelectorAll(sectionSelector);
    if (options.includeFirstSectionInFirstPage) {
      // 保留第一张表，其余移除
      nodes.forEach((n, idx) => {
        if (idx > 0) n.remove();
      });
    } else {
      // 移除全部表格，仅保留标题+统计卡片
      nodes.forEach((n) => n.remove());
    }
    document.body.appendChild(firstPageClone);
    await new Promise((res) => requestAnimationFrame(res));
    const firstCanvas = await html2canvas(firstPageClone, {
      scale: options.scale || 1,
      useCORS: true,
    });
    document.body.removeChild(firstPageClone);
    addCanvas(firstCanvas);

    // ------------- 后续 section 每页 -------------
    const startIdx = options.includeFirstSectionInFirstPage ? 1 : 0;
    for (let i = startIdx; i < sections.length; i++) {
      pdf.addPage();
      const sec = sections[i];
      const secClone = sec.cloneNode(true);
      secClone.style.width = sec.clientWidth + "px";
      document.body.appendChild(secClone);
      await new Promise((res) => requestAnimationFrame(res));
      const secCanvas = await html2canvas(secClone, {
        scale: options.scale || 1,
        useCORS: true,
      });
      document.body.removeChild(secClone);
      addCanvas(secCanvas);
    }
  } else {
    // 若无 section，直接整体截图
    const clone = rootEl.cloneNode(true);
    clone.style.width = rootEl.clientWidth + "px";
    document.body.appendChild(clone);
    await new Promise((res) => requestAnimationFrame(res));
    const canvas = await html2canvas(clone, {
      scale: options.scale || 1,
      useCORS: true,
    });
    document.body.removeChild(clone);
    addCanvas(canvas);
  }

  pdf.save(filename);
}
